import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import EnhanceLog from 'vite-plugin-enhance-log'
import viteCompression from 'vite-plugin-compression'
import { viteMockServe } from 'vite-plugin-mock'

const proxyUrl = 'http://192.168.0.87:60063' //测试环境

export default defineConfig({
    build: {
        assetsDir: 'static',
        target: ['chrome78', 'chrome52', 'chrome49', 'chrome65'],
        chunkSizeWarningLimit: 1000,
        minify: 'terser',
        cssCodeSplit: true,
        terserOptions: {
            compress: {
                drop_console: true,
                drop_debugger: true, //打包时删除 debugger
            },
            output: {
                comments: true, // 去掉注释内容
            },
        },
        rollupOptions: {
            output: {
                manualChunks(id) {
                    if (id.includes('node_modules')) {
                        // 让每个插件都打包成独立的文件
                        return id.toString().split('node_modules/')[1].split('/')[0].toString()
                    }
                },
            },
        },
        brotliSize: false,
    },
    base: './',
    css: {
        preprocessorOptions: {
            less: {
                javascriptEnabled: true,
            },
        },
    },
    plugins: [
        vue(),
        vueJsx(),
        viteCompression(),
        EnhanceLog({
            splitBy: ';',
        }),
        viteMockServe({
            mockPath: 'src/mock',
            localEnabled: true, // 开发环境启用 mock
            logger: true,
            supportTs: false, // 打开后，可以读取 ts 文件模块。 请注意，打开后将无法监视.js 文件。
            watchFiles: true, // 监视文件更改
        }),
    ],
    resolve: {
        alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url)),
            'vue': 'vue/dist/vue.esm-bundler.js',
        },
    },
    server: {
        port: 3031,
        host: '0.0.0.0',
        open: true,
        hmr: {
            overlay: true,
        },
        proxy: {
            '/ups': {
                target: proxyUrl,
                changeOrigin: true,
                rewrite: (path) => path.replace(/^\/api/, ''),
            },
            '/model': {
                target: 'http://192.168.10.178',
                changeOrigin: true,
                rewrite: (path) => path.replace(/^\/api/, ''),
            },
        },
    },
})
